<template>
    <div class="cesium-marker" :id="id"></div>
</template>

<script setup lang="ts">
import { uuidv4 } from '@/utils/uuidv4'
import {
    useContextViewer,
    useContextPinBuilder
} from './hooks/useCesiumContext'
import IconList from '@/common/IconList'
import { watch } from 'vue'
import { onBeforeUnmount } from 'vue'
interface Props {
    color: Cesium.Color
    position: number[]
    name: string
}

defineOptions({
    name: 'cesium-marker',
})

const props = withDefaults(defineProps<Props>(), {
    color: () => Cesium.Color.RED,
    position: () => [10, 10, 10],
    name: '你好',
})

const viewerRef = useContextViewer()

const pinbuilderRef = useContextPinBuilder()

let marker = pinbuilderRef?.value.fromUrl(IconList.Crosshair, props.color, 48)

if (marker instanceof Promise) {
    marker = await marker
}

const id = uuidv4()

const entity = new Cesium.Entity({
    id: id,
    position: Cesium.Cartesian3.fromDegrees(
        props.position[0],
        props.position[1],
        props.position?.[2],
    ),
    billboard: {
        image: marker,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        color: Cesium.Color.WHITE,
        scale: 0.83,
        alignedAxis: Cesium.Cartesian3.ZERO, // default
    },
    label: {
        fillColor: Cesium.Color.WHITE,
        font: 'bold 8pt Segoe UI Semibold',
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        outlineColor: Cesium.Color.BLACK,
        outlineWidth: 3,
        pixelOffset: new Cesium.Cartesian2(0, -65),
        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        // 文字内容
        text: props.name,
        // 垂直原点
        verticalOrigin: Cesium.VerticalOrigin.TOP,
    },
})

watch(
    () => viewerRef?.value,
    (n, o) => {
        if (!n?.entities.contains(entity)) {
            n?.entities.add(entity)
        }
    },
)

onBeforeUnmount(() => {

    console.log('on onBeforeUnmount');

    if (viewerRef?.value.entities.contains(entity)) {
        viewerRef.value.entities.remove(entity)
    }
})
</script>
